import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

/**
 * 检查数据库连接状态的API路由
 */
export async function GET(request: NextRequest) {
  try {
    // 获取URL参数
    const url = new URL(request.url);
    const action = url.searchParams.get('action');
    
    // 执行简单查询以验证连接
    const result = await prisma.$queryRaw`SELECT 1+1 AS result`;
    
    // 检查数据库连接
    const dbInfo = {
      connection: 'connected',
      provider: prisma._engineConfig?.activeProvider || 'unknown',
      result: result,
      timestamp: new Date().toISOString(),
      query: 'SELECT 1+1 AS result'
    };
    
    return NextResponse.json({
      status: 'success',
      message: '数据库连接正常',
      data: dbInfo
    });
  } catch (error) {
    console.error('数据库连接检查失败:', error);
    return NextResponse.json(
      { 
        status: 'error', 
        message: '数据库连接失败', 
        error: error instanceof Error ? error.message : String(error)
      },
      { status: 500 }
    );
  }
}

/**
 * 直接更新文档的测试API
 */
export async function POST(request: NextRequest) {
  try {
    // 解析请求体
    const data = await request.json();
    const { documentId, projectId, title, content } = data;
    
    if (!documentId || !projectId) {
      return NextResponse.json(
        { status: 'error', message: '缺少必要参数' },
        { status: 400 }
      );
    }
    
    console.log('直接更新文档API收到请求:', {
      documentId,
      projectId,
      hasTitle: !!title,
      hasContent: !!content
    });
    
    // 获取当前文档
    const document = await prisma.document.findUnique({
      where: {
        id: documentId,
        projectId
      }
    });
    
    if (!document) {
      return NextResponse.json(
        { status: 'error', message: '文档不存在' },
        { status: 404 }
      );
    }
    
    console.log('找到文档:', {
      id: document.id,
      title: document.title,
      version: document.version
    });
    
    // 直接更新文档
    try {
      const updatedDocument = await prisma.document.update({
        where: {
          id: documentId
        },
        data: {
          title: title || document.title,
          content: content || document.content,
          version: (document.version || 0) + 1,
          updatedAt: new Date()
        }
      });
      
      console.log('文档更新成功:', {
        id: updatedDocument.id,
        title: updatedDocument.title,
        version: updatedDocument.version
      });
      
      return NextResponse.json({
        status: 'success',
        message: '文档更新成功',
        data: {
          id: updatedDocument.id,
          title: updatedDocument.title,
          version: updatedDocument.version,
          updatedAt: updatedDocument.updatedAt
        }
      });
    } catch (updateError) {
      console.error('文档更新失败:', updateError);
      return NextResponse.json(
        { 
          status: 'error', 
          message: '文档更新失败', 
          error: updateError instanceof Error ? updateError.message : String(updateError)
        },
        { status: 500 }
      );
    }
  } catch (error) {
    console.error('数据库操作失败:', error);
    return NextResponse.json(
      { 
        status: 'error', 
        message: '数据库操作失败', 
        error: error instanceof Error ? error.message : String(error)
      },
      { status: 500 }
    );
  }
} 